<template>
  <div class="cms-channel-dialog-container">
    <el-dialog :title="state.dialog.title" v-model="state.dialog.isShowDialog" width="769px">
      <el-form ref="cmsChannelDialogFormRef" :model="state.ruleForm" :rules="rules" size="default" label-width="90px">
        <el-row :gutter="35">
          <el-col :xs="24" :sm="24" :md="24" :lg="24" :xl="24" class="mb20">
            <el-form-item label="所属机构" prop="orgId">
              <el-tree-select
                  v-model="state.ruleForm.orgId"
                  :data="state.sysOrgData"
                  :render-after-expand="false"
                  style="width: 500px"
                  check-strictly
                  filterable
                  @change="orgChange"
              />
            </el-form-item>
          </el-col>
          <el-col :xs="24" :sm="24" :md="24" :lg="24" :xl="24" class="mb20" style="display: none">
            <el-form-item label="上级栏目" prop="parentId">
              <el-tree-select
                  v-model="state.ruleForm.parentId"
                  :data="state.channelTreeData"
                  :render-after-expand="true"
                  style="width: 500px"
                  check-strictly
                  filterable
              />
            </el-form-item>
          </el-col>
          <el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20">
            <el-form-item label="栏目名称" prop="channelName">
              <el-input v-model="state.ruleForm.channelName" placeholder="请输入栏目名称" clearable></el-input>
            </el-form-item>
          </el-col>
          <el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20">
            <el-form-item label="排序" prop="channelOrder">
              <el-input-number v-model="state.ruleForm.channelOrder" :min="0" :max="999" controls-position="right"
                               placeholder="请输入排序" class="w100"/>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <template #footer>
				<span class="dialog-footer">
					<el-button @click="onCancel" size="default">取 消</el-button>
					<el-button type="primary" @click="onSubmit(cmsChannelDialogFormRef)" size="default">{{ state.dialog.submitTxt }}</el-button>
				</span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts" name="channelDialog">
import {nextTick, onMounted, reactive, ref} from 'vue';
import {ElMessage, FormInstance, FormRules} from "element-plus";
import {useChannelApi} from "/@/api/cms/channel";
import {systemApi} from "/@/api/system";

// 定义子组件向父组件传值/事件
const emit = defineEmits(['refresh']);
const props = defineProps(['orgId', 'orgTree', 'channelTree']);
const {add, edit, channelTree} = useChannelApi();
const {orgTree} = systemApi();
const orgChange = async (val: string) => {
  if (val) {
    state.ruleForm.orgId = val;
    await loadChannelTree();
  }
};
// 定义变量内容
const cmsChannelDialogFormRef = ref();
const state = reactive({
  ruleForm: {
    id: '',
    orgId: '',
    channelName: '',
    channelOrder: 1,
    parentId: '0',
    tenantId: '',
  },
  sysOrgData: [] as OrgTreeType[], // 机构数据
  channelTreeData: [] as OrgTreeType[], // 栏目数据
  dialog: {
    isShowDialog: false,
    type: '',
    title: '',
    submitTxt: '',
  }
});
const loadChannelTree = async () => {
  if (props.orgId) {
    const res = await channelTree({orgId: props.orgId});
    if (res.status === 200) {
      state.channelTreeData = res.data;
    }
  }
};

const clearForm = () => {
  state.ruleForm = {
    id: '',
    orgId: '',
    channelName: '',
    channelOrder: 1,
    parentId: '0',
    tenantId: '',
  }
}

onMounted(async () => {
  await loadChannelTree()
})

// 打开弹窗
const openDialog = async (type: string, row: RowCmsChannelType) => {
  state.sysOrgData = props.orgTree;
  if (type === 'edit') {
    state.dialog.title = '修改栏目';
    state.dialog.submitTxt = '修 改';
    state.ruleForm = row;
    state.ruleForm.channelName = row.label;
    state.ruleForm.channelOrder = row.orderNo;
    state.ruleForm.orgId = props.orgId;
    console.log('update', state.ruleForm)
  } else {
    state.dialog.title = '新增机构';
    state.dialog.submitTxt = '新 增';
    clearForm()
    // 清空表单，此项需加表单验证才能使用
    // await nextTick(() => {
    //   if (cmsChannelDialogFormRef.value) {
    //     cmsChannelDialogFormRef.value.resetFields();
    //   }
    // });
  }
  state.dialog.isShowDialog = true;
};
// 关闭弹窗
const closeDialog = () => {
  state.dialog.isShowDialog = false;
};
// 取消
const onCancel = () => {
  closeDialog();
};

const rules = reactive<FormRules<any>>({
  orgId: [
    {required: true, message: '请选择栏目所属机构(教育局)', trigger: 'change'},
  ],
  channelName: [
    {required: true, message: '栏目名称不能为空', trigger: 'blur'},
    {min: 3, max: 10, message: '栏目名称长度应该在3到10个字符之间', trigger: 'blur'},
  ],
  channelOrder: [
    {required: true, message: '栏目序号不能为空'},
    {type: 'number', message: '栏目序号必须为数字'},
  ],
  // parentId: [
  //   {required: true, message: '上级栏目不能为空', trigger: 'blur'},
  //   {min: 3, max: 50, message: '应用描述长度,至少3个字符，最多50个字符', trigger: 'blur'},
  // ]
})

// 提交
const onSubmit = async (formEl: FormInstance | undefined) => {
  if (!formEl) return
  await formEl.validate(async (valid, fields) => {
    if (!valid) {
      console.log('error submit!!', fields);
      ElMessage.error('数据校验失败!');
      return false;
    }
    const res = await state.ruleForm.id ? await edit(state.ruleForm) : await add(state.ruleForm)
    if (res.status === 200) {
      ElMessage.success('保存成功');
      await loadChannelTree()
    }
    closeDialog();
    emit('refresh');
    // if (state.dialog.type === 'add') { }
  });
};

// 暴露变量
defineExpose({
  openDialog,
});
</script>
